package cn.shyouchi.wuguanjia.android.ui.attendance.signin;

import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.attendance.AttendanceApi;
import cn.shyouchi.wuguanjia.android.controls.AttendanceResDialog;
import cn.shyouchi.wuguanjia.android.event.SignInEvent;
import cn.shyouchi.wuguanjia.android.event.SignStateEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceEntity;
import cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceTokePhotoActivity;
import cn.shyouchi.wuguanjia.android.ui.attendance.BaseAttendanceActivity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceTokePhotoActivity.REQUEST_CODE;
import static cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceTokePhotoActivity.REQUEST_CODE_NEED_EXTRA;
import static cn.shyouchi.wuguanjia.android.ui.attendance.AttendanceTokePhotoActivity.RESULT_CODE;

public class SignInActivity extends BaseAttendanceActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.tv_sel_rank)
    TextView mTvSelRank;
    @BindView(R.id.btn_take_photo)
    Button mBtnTakePhoto;


    AttendanceApi mAttendanceApi;

    AttendanceEntity.ResultMessageBean mAttendanceEntity;
    PopupMenu menu;
    boolean locationSuc = false;
    int type = 1;

    String addr = "";

    String path;

    String extraMsg = "";

    @Override
    public int initContentView() {
        return R.layout.activity_sign_in;
    }

    @Override
    public void initInjector() {
        mAttendanceApi = new AttendanceApi(mContext);
        mAttendanceEntity = getIntent().getParcelableExtra("attendance");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        this.registerForContextMenu(mTvSelRank);
        EventBus.getDefault().register(this);
        if (mAttendanceEntity != null) {
            initAttendance(mAttendanceEntity);
        }
    }

    private void initAttendance(AttendanceEntity.ResultMessageBean entity) {
        menu = new PopupMenu(mContext, mTvSelRank);
        initPopRank(entity);
        mTvSelRank.setText(entity.getService().getServicesname());
        mAttendanceApi.getCheckAttendance()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AttendanceInfoEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.showToast("获取考勤范围失败");
                    }

                    @Override
                    public void onNext(AttendanceInfoEntity entity) {
                        onSignCircleChange(entity.getResultMessage().getLatLng(), entity.getResultMessage().getAttendancescope(), entity.getResultMessage().getAddress());
                    }
                });


        if (entity.getCheckin().hasSignIn()) {
            setSignedState();
        }


    }


    @OnClick(R.id.btn_take_photo)
    public void onClick() {


        startActivityForResult(new Intent(mContext, AttendanceTokePhotoActivity.class), REQUEST_CODE);


    }

    @OnClick(R.id.tv_sel_rank)
    public void onSelRankClick(View v) {
        showSelRankPop();
    }

    @Override
    public int initMapView() {
        return R.id.map;
    }

    @Override
    public void onTimeChange(long time) {
        mTvTime.setText(new SimpleDateFormat("HH:mm").format(time));
    }

    private void initPopRank(final AttendanceEntity.ResultMessageBean entity) {
        final String name = entity.getService().getServicesname();
        menu.getMenu().add(name);
        menu.getMenu().add("外出");
        menu.getMenu().add("借调");
        menu.getMenu().add("实习");
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                mTvSelRank.setText(item.getTitle());
                switch (item.getTitle().toString()) {
                    case "外出":
                        type = 2;
                        break;
                    case "借调":
                        type = 3;
                        break;
                    case "实习":
                        type = 4;
                        break;
                    default:
                        type = 1;
                        break;
                }
                return true;
            }
        });
        menu.setGravity(Gravity.TOP);
    }


    private void showSelRankPop() {
        menu.show();
    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        super.onLocationChanged(location);
        addr = location.getAddress();
        mTvLocation.setText(addr);
    }

    @Override
    public void onLocationStart() {
        super.onLocationStart();
        mTvLocation.setText("正在定位...");
    }

    @Override
    public void onLocationStop(boolean success) {
        super.onLocationStop(success);
        locationSuc = success;
        if (!success) {
            mTvLocation.setText("定位失败");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            path = data.getStringExtra("path");
            if (type == 2) {
                startActivityForResult(new Intent(mContext, SignExtraMsgActivity.class), REQUEST_CODE_NEED_EXTRA);
            } else {
                signIn(path);
            }
        } else if (requestCode == REQUEST_CODE_NEED_EXTRA && resultCode == RESULT_CODE) {
            extraMsg = data.getStringExtra("extra_msg");
            signIn(path);
        }
    }

    private void signIn(String path) {


        Map<String, RequestBody> paramsMap = new HashMap<>();

        final RequestBody projectsIdBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(mAttendanceEntity.getService().getId()));
        paramsMap.put("serviceid", projectsIdBody);
        final RequestBody IdBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(type));
        paramsMap.put("type", IdBody);
        final RequestBody nameBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(mLocationMarker.getPosition().latitude));
        paramsMap.put("latitude", nameBody);
        final RequestBody ageBody = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(mLocationMarker.getPosition().longitude));
        paramsMap.put("longitude", ageBody);
        final RequestBody heightBody = RequestBody.create(MediaType.parse("multipart/form-data"), addr);
        paramsMap.put("address", heightBody);


        if (type == 2 && !TextUtils.isEmpty(extraMsg)) {
            final RequestBody desBody = RequestBody.create(MediaType.parse("multipart/form-data"), extraMsg);
            paramsMap.put("description", desBody);
        }


        mAttendanceApi.signIn(paramsMap, path)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseRequestResult>() {
                    @Override
                    public void onCompleted() {
                        EventBus.getDefault().post(new SignStateEvent());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        AttendanceResDialog.newInstance("签到结果", "签到失败！\n" + e.getMessage(), String.valueOf(1)).show(getFragmentManager(), "signin");
                    }

                    @Override
                    public void onNext(BaseRequestResult result) {
                        if (result.getResultMessage().equals("恭喜你签到第1名")) {
                            AttendanceResDialog.newInstance("签到结果", "签到成功！\n" + result.getResultMessage(), String.valueOf(2)).show(getFragmentManager(), "signin");
                        }
//                        else if (result.getResultMessage().equals("恭喜你签到第1名")) {
//                            AttendanceResDialog.newInstance("签到结果", "签到成功！\n" + result.getResultMessage(), String.valueOf(3)).show(getFragmentManager(), "signin");
//                        }
                        else {
                            AttendanceResDialog.newInstance("签到结果", "签到成功！\n" + result.getResultMessage(), String.valueOf(0)).show(getFragmentManager(), "signin");
                        }
                    }
                });
    }


    private String getRankNameByType(int t) {
        String name = mAttendanceEntity.getService().getServicesname();
        switch (t) {
            case 2:
                name = "外出";
                break;
            case 3:
                name = "借调";
                break;
            case 4:
                name = "实习";
                break;
        }
        return name;
    }

    private void setSignedState() {
        mBtnTakePhoto.setEnabled(false);
        mBtnTakePhoto.setText("今天已签到");
        mTvSelRank.setEnabled(false);
        mTvSelRank.setText(getRankNameByType(mAttendanceEntity.getCheckin().getType()));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignStateChange(SignInEvent event) {
        if (event.signed) {
            setSignedState();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
